using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using CoachingOrganizer.Toolkit.Collections.Helpers;
using CoachingOrganizer.Logic.Models.Common;

namespace CoachingOrganizer.Android.Adapters
{
    public class GoalsAdapter : BaseAdapter
    {
        private Activity _context;
        private List<GoalModel> _items = new List<GoalModel>();
        private PeriodModel _model;

        public GoalsAdapter(Activity context, PeriodModel model)
        {
            _context = context;
            _model = model;
            model.GoalsChanged += Model_GoalsChanged;
            model.GoalsCollectionChanged += Model_GoalsCollectionChanged;
            if (model.Goals != null)
                _items = model.Goals.ToList();
        }

        public override Java.Lang.Object GetItem(int position)
        {
            return position;
        }

        public override long GetItemId(int position)
        {
            return position;
        }

        public override int Count
        {
            get { return _items.Count; }
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View view = _context.LayoutInflater.Inflate(Resource.Layout.GoalLayout, parent, false);
            HookModelToView(view, _items[position]);
            return view;
        }

        private void HookModelToView(View view, GoalModel goalModel)
        {
            //view.Click += (sender, e) => _model.CurrentGoal = goalModel;
            Button detailsButton = view.FindViewById<Button>(Resource.Id.detailsButton);
            detailsButton.Click += (sender, e) => _model.CurrentGoal = goalModel;
            TextView titleTextView = view.FindViewById<TextView>(Resource.Id.goalTitleTextView);
            titleTextView.Text = goalModel.Title;
            Button saveButton = view.FindViewById<Button>(Resource.Id.saveGoalButton);
            saveButton.Click += (sender, e) => goalModel.Save();
            Button removeButton = view.FindViewById<Button>(Resource.Id.removeGoalButton);
            removeButton.Click += (sender, e) => goalModel.Remove();
        }

        private void Model_GoalsChanged(object sender, EventArgs e)
        {
            _context.RunOnUiThread(() =>
            {
                _items = _model.Goals.ToList();
                NotifyDataSetChanged();
            });
        }

        private void Model_GoalsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            _context.RunOnUiThread(() =>
            {
                ObservableCollectionHelper.ApplyChanges(e, _items);
                NotifyDataSetChanged();
            });
        }
    }
}